package monitor

import (
	"fmt"
	"sync"
)

type ServerData struct {
	Hostname       string    `json:"hostname"`
	EventTime      int64     `json:"event_time"`
	TotalCPUUsage  float64   `json:"total_cpu_usage"`
	MemTotal       uint64    `json:"mem_total"`
	MemAvailable   uint64    `json:"mem_available"`
	MemUsed        uint64    `json:"mem_used"`
	MemFree        uint64    `json:"mem_free"`
	MemUsedPercent float64   `json:"mem_used_percent"`
	CoreUsages     []float64 `json:"core_usages"`
}

type TimeSeries struct {
	Time       int64
	TimeSeries string
	Value      string
	DataType   string
}

type ReportHosts struct {
	mu              sync.RWMutex
	HostDeviceNames map[string]HostInfo `json:"host_device_names"`
}

type HostInfo struct {
	Hostname  string `json:"hostname"`
	Path      string `json:"path"`
	CPUNumber int    `json:"cpuNumber"`
}

func (s *ServerData) toHostInfo() *HostInfo {
	hi := &HostInfo{
		Hostname:  s.Hostname,
		Path:      fmt.Sprintf("root.vms.%v", s.Hostname),
		CPUNumber: len(s.CoreUsages),
	}
	return hi
}

// Hosts 初始化一个空的 ReportHosts 对象
var Hosts = &ReportHosts{
	HostDeviceNames: make(map[string]HostInfo),
}

func (r *ReportHosts) SetHostInfo(key string, info HostInfo) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.HostDeviceNames[key] = info
}

func (r *ReportHosts) GetHostInfo(key string) (HostInfo, bool) {
	r.mu.RLock()
	defer r.mu.RUnlock()
	info, exists := r.HostDeviceNames[key]
	return info, exists
}

func (r *ReportHosts) DeleteHostInfo(key string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	delete(r.HostDeviceNames, key)
}

func (r *ReportHosts) AddHostInfoIfNotExists(key string, s ServerData) bool {
	info := s.toHostInfo()
	r.mu.Lock()
	defer r.mu.Unlock()
	if _, exists := r.HostDeviceNames[key]; exists {
		return false
	}
	r.HostDeviceNames[key] = *info
	return true
}

// ListHosts 返回当前主机列表
func (r *ReportHosts) ListHosts() []HostInfo {
	r.mu.RLock()
	defer r.mu.RUnlock()

	var hostList []HostInfo
	for _, info := range r.HostDeviceNames {
		hostList = append(hostList, info)
	}
	return hostList
}
